package edu.neu.highway.service.impl;

import com.influxdb.client.InfluxDBClient;
import com.influxdb.query.FluxTable;
import edu.neu.highway.service.IFluxQueryService;
import edu.neu.highway.utils.FluxUtils;
import edu.neu.highway.vo.flux.FluxQueryParams;
import edu.neu.highway.vo.flux.FluxQueryResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class FluxQueryServiceImpl implements IFluxQueryService {

    private final InfluxDBClient influxDBClient;

    private final Pattern pattern;

    public FluxQueryServiceImpl(InfluxDBClient influxDBClient) {
        this.influxDBClient = influxDBClient;
        this.pattern = Pattern.compile("start: (\\d+), stop: (\\d+)");
    }

    @Override
    public FluxQueryResult queryFlowByFlux(String fluxQuery) {
        // 1, 执行查询
        List<FluxTable> tables = influxDBClient.getQueryApi().query(fluxQuery);
        // 2, 从 flux 语句中提取开始时间和技术时间
        Matcher matcher = pattern.matcher(fluxQuery);
        String startTimeStr = "0";
        String stopTimeStr = "0";
        if (matcher.find()) {
            startTimeStr = matcher.group(1);
            stopTimeStr = matcher.group(2);
        }
        // 3, 解析 flux 查询结果，生成返回值对象
        FluxQueryParams fluxQueryParams = new FluxQueryParams();
        fluxQueryParams.setStop(Integer.parseInt(stopTimeStr));
        fluxQueryParams.setStart(Integer.parseInt(startTimeStr));
        return FluxUtils.buildFluxQueryResult(tables, fluxQueryParams);
    }

    @Override
    public FluxQueryResult queryFlowByParams(FluxQueryParams params) {
        // 1, 解析 Flux 查询参数，生成 Flux 查询语句
        String fluxQueryStr = FluxUtils.buildFluxQueryString(params);
        log.info("flux query:\n{}", fluxQueryStr);
        // 2, 执行查询
        List<FluxTable> tables = influxDBClient.getQueryApi().query(fluxQueryStr);

        // 3, 解析 flux 查询结果，生成返回值对象
        return FluxUtils.buildFluxQueryResult(tables, params);
    }
}
